package com.yanqu.road.dao.impl.player;

import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.impl.TempDataObjectDao;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UserCommonActivityDaoImpl extends TempDataObjectDao<UserActivityConditionData> {

    public Map<Integer, Map<Integer, List<UserActivityConditionData>>> getUserActivityConditionDataMap(long userId, List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, List<UserActivityConditionData>>> dataMap = new ConcurrentHashMap<>();
        if(null != activityIdList && activityIdList.size() > 0) {
            String condition = "activityId in(" + StringUtils.listToString(activityIdList, ",") + ") and userId=?";
            String sql = "select * from t_u_common_activity_condition where " + condition;
            try {
                getDb().setConnName(DbNameStrategy.getUserDb());
                call = getDb().getConnection().prepareCall(sql);
                call.setLong(1, userId);
                rs = call.executeQuery();
                while (rs.next()) {
                    UserActivityConditionData data = parse(rs);
                    if (!dataMap.containsKey(data.getActivityId())) {
                        dataMap.put(data.getActivityId(), new ConcurrentHashMap<>());
                    }
                    Map<Integer, List<UserActivityConditionData>> tempMap = dataMap.get(data.getActivityId());
                    if (!tempMap.containsKey(data.getType())) {
                        tempMap.put(data.getType(), new ArrayList<>());
                    }
                    tempMap.get(data.getType()).add(data);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                getDb().closeConnection(call, rs);
            }
        }
        return dataMap;
    }

    public List<UserActivityConditionData> getUserActivityConditionDataList(int activityId, long userId, int type) {
        ResultSet rs = null;
        CallableStatement call = null;
        List<UserActivityConditionData> dataList = new ArrayList<>();
        String sql = "select * from t_u_common_activity_condition where activityId=? and type=? and userId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, type);
            call.setLong(3, userId);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public List<UserActivityConditionData> getUserActivityConditionDataList(int activityId, int type, int rankNum){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_common_activity_condition where activityId=? and type=? order by value+0 desc limit ?";
        List<UserActivityConditionData> dataList = new ArrayList<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, type);
            call.setInt(3, rankNum);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataList.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataList;
    }

    public Map<Long, UserActivityConditionData> getUserActivityConditionDataMap(int activityId, int type){
        ResultSet rs = null;
        CallableStatement call = null;
        String sql = "select * from t_u_common_activity_condition where activityId=? and type=?";
        Map<Long, UserActivityConditionData> dataMap = new ConcurrentHashMap<>();
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareCall(sql);
            call.setInt(1, activityId);
            call.setInt(2, type);
            rs = call.executeQuery();
            while (rs.next()) {
                UserActivityConditionData data = parse(rs);
                dataMap.put(data.getUserId(), data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    @Override
    protected boolean addData(UserActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "insert into t_u_common_activity_condition(userId,activityId,conditionId,preValue,value,isGetReward,modifyTime,type) values "
                + "(?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getConditionId());
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getModifyTime());
            call.setInt(i++, data.getType());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected boolean updateData(UserActivityConditionData data) {
        PreparedStatement call = null;
        String sql = "update t_u_common_activity_condition set preValue=?,value=?,isGetReward=?,modifyTime=? where activityId=? and " +
                "type=? and userId=? and conditionId=?";
        try {
            getDb().setConnName(DbNameStrategy.getUserDb());
            call = getDb().getConnection().prepareStatement(sql);
            int i = 1;
            call.setString(i++, data.getPreValue().toString());
            call.setString(i++, data.getValue().toString());
            call.setBoolean(i++, data.isGetReward());
            call.setLong(i++, data.getModifyTime());
            call.setInt(i++, data.getActivityId());
            call.setInt(i++, data.getType());
            call.setLong(i++, data.getUserId());
            call.setInt(i++, data.getConditionId());
            return call.executeUpdate() > 0;
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        } finally {
            getDb().closeConnection(call, null);
        }
        return false;
    }

    @Override
    protected UserActivityConditionData parseData(ResultSet rs) throws SQLException {
        UserActivityConditionData data = new UserActivityConditionData();
        data.setUserId(rs.getLong("userId"));
        data.setActivityId(rs.getInt("activityId"));
        data.setConditionId(rs.getInt("conditionId"));
        String value = rs.getString("preValue");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setPreValue(new BigInteger(value));
        }
        value = rs.getString("value");
        data.setValue(new BigInteger(value));
        data.setGetReward(rs.getBoolean("isGetReward"));
        data.setModifyTime(rs.getLong("modifyTime"));
        data.setType(rs.getInt("type"));
        return data;
    }
}
